package com.bestcem.xm.component.swagger.configure;

import com.bestcem.xm.component.swagger.properties.SwaggerProperties;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.*;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;

import static java.util.Collections.singletonList;

@Slf4j
@Configuration
@EnableConfigurationProperties({SwaggerProperties.class})
@ConditionalOnProperty(prefix = "xm.swagger", name = "enabled", havingValue = "true")
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerAutoConfiguration {

    private static final String TOKEN_HEADER = "Authorization";

    @Value("${server.port}")
    private int port;
    @Value("${server.servlet.context-path:}")
    private String contextPath;

    private static final String VERSION = "1.0.0";

    private SwaggerProperties swaggerProperties;

    @Autowired
    public SwaggerAutoConfiguration(SwaggerProperties swaggerProperties) {
        this.swaggerProperties = swaggerProperties;
    }


    @Bean
    @ConditionalOnMissingBean
    @SneakyThrows
    public Docket createRestApi() {
        List<SecurityScheme> securitySchemes = singletonList(new ApiKey(TOKEN_HEADER, TOKEN_HEADER, "header"));
        List<SecurityContext> securityContexts = singletonList(
                SecurityContext.builder()
                        .securityReferences(securityReferences())
                        .operationSelector(operationContext -> true)
                        .build()
        );

        Docket docket = new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                //.globalResponses(HttpMethod.GET, globalResponse())
                //.globalResponses(HttpMethod.POST, globalResponse())
                //.globalRequestParameters(getGlobalRequestParameters())
                .securitySchemes(securitySchemes)
                .securityContexts(securityContexts)
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
        // 控制台输出Swagger3接口文档地址
        log.info("Swagger3接口文档地址: http://ip:{}{}/swagger-ui/index.html", port, contextPath);
        // 控制台输出Knife4j增强接口文档地址
        log.info("Knife4j增强接口文档地址: http://ip:{}{}/doc.html", port, contextPath);
        return docket;
    }

    private List<SecurityReference> securityReferences() {
        AuthorizationScope[] authorizationScopes =
                new AuthorizationScope[]{new AuthorizationScope("global", "accessEverything")};

        SecurityReference reference = new SecurityReference(TOKEN_HEADER, authorizationScopes);
        return singletonList(reference);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDescription())
                .version(VERSION)
                .build();
    }

    private List<RequestParameter> getGlobalRequestParameters() {
        List<RequestParameter> parameters = new ArrayList<>();
        parameters.add(new RequestParameterBuilder()
                .name("authorization")
                .description("token")
                .required(true)
                .in(ParameterType.HEADER)
                .build());
        return parameters;
    }

    private List<Response> globalResponse() {
        List<Response> responseList = new ArrayList<>();
        responseList.add(new ResponseBuilder().code("401").description("未认证").build());
        responseList.add(new ResponseBuilder().code("403").description("请求被禁止").build());
        responseList.add(new ResponseBuilder().code("404").description("找不到资源").build());
        return responseList;
    }

}
